var watchlistEditDialog = function(container,config,callback){//{columns:[]}
    this.container  =container||$("body");
	var qslan=QS_Lang.watchlist;
    this.isOpen = false;
    this.cacheObj=null;
    this.datagridWrapEl = null;
    this.editEl = null;
    this.selectRowKey = null;
    this.currentAddKey = null;//auto complete(126:IBM)
    this.currentEditDom = null;
    this.editInput = null;
    this.callback={
        editData:function(obj){
            
        },
        createData:function(obj){
            
        }
    };
    this.config={
        columns:[{
            header: qslan["name"],
            dataIndex: 'name',
            width: 90
        }, {
            header: qslan["numofshares"],
            dataIndex: 'shares',
            width: 100
        }, {
            header: qslan["purchasedate"],
            dataIndex: 'pdate',
            width: 110
        }, {
            header: qslan["purchaseprice"],
            dataIndex: 'pprice',
            width: 110
        }, {
            header: qslan["commission"],
            dataIndex: 'commission',
            width: 100
        }, {
            header: "",
            dataIndex: 'remove',
            renderer: '<a href="javascript:void(0)">Remove</a>',
            type: 'remove',
            width: 30
        }],
        ACP:true
    };
    $.extend(this.config,config);
    $.extend(this.callback,callback);
    this.datagrid = null;
    this.edittingData = {};
    this.cmd = {
        ADD: '1',
        EDIT: '2',
        DEL: '3'
    };
    this.operateStack = {
        '1': {},
        '2': {},
        '3': {}
    };
    this.newholdingID = -1;
    this.maxRank = 0;
    this._init();
};
watchlistEditDialog.prototype = {
    _createUI:function(){
        var self=this;
        this.datagridWrapEl = this.el.find('div.datagridWrap');
        this.datagrid = this._buildDataGrid(self.datagridWrapEl);
        // this.datagrid.el.find(".rtq-scrollbar-y").bind("mousedown.edit", function(){
        //     self._activeFirstRow();
        // });
        this.datagrid.el.append("<div class='wled-row-one-mask'>"+QS_Lang.watchlist["addtickerprompt"]+"</div>");
        this.datagridHeadHeight = this.datagrid.el.find(".rtq-grid-hd").height();
        this._buildEditRow();
        this.datagridWrapEl.find(".wled-row-one-mask").bind("click.edit", function(){
            self.el.find(".datagridWrap .rtq-grid-row-selected").removeClass("rtq-grid-row-selected");
            self._activeFirstRow();
            self.editEl.show();
        });
        this.editInput = self.editEl.find("#wled_ticker");
        this._bindACPandCal();
        this.el.find(".operator").bind("click.edit", function(e){
            var target = $(e.target);
            if (target.hasClass('save')) {
                if (self._saveToWatchList(e)) {
                    self.hide();
                }
            }
            else 
                if (target.hasClass('cancel')) {
                    self.hide();
                }
        });
    },
	setCallback:function(callback){
		$.extend(this.callback,callback);
	},
    _init: function(){
        if (typeof tickerValidation == 'function') {
            this.tValidation = new tickerValidation(100, "watchlistEditDialog", "tValidation");
        }
        var self = this,qslan=QS_Lang.watchlist;
        var html = '<div class="rtq-ptf-editor"><div class="hd clearfix"><div class="operator"><h3>'+qslan["entername"]+'</h3><input type="text" name="" class="qs-ui-ipt" value="" size="20" /></div></div>' +
        '<div class="bd"><div class="datagridWrap rtq-wl"></div><div class="pl-wrap"></div></div>' +
        '<div class="ft"><div class="operator"><a class="qs-ui-btn save" href="#">'+qslan["save"]+'</a><a class="qs-ui-btn cancel" href="#">'+qslan["cancel"]+'</a></div></div></div>';
        if (typeof Util.RtqWindow != 'function') {
              this.el=$(html).appendTo(this.container);
              this._createUI();
              this.container.hide();
        }
        else {
            this.win = new Util.RtqWindow(document.body, {
                windowReady: function(obj){
                    obj.setHtml(html);
                    self.el = obj.el.find(".rtq-ptf-editor");
                    self._createUI();
                }
            }, {
                title: qslan["edit"]+" "+QS_Lang.watchlist["wl"],
                top: 100,
                width: 556,
                height: 418,
                resizable: false,
                isGlobal: true,
                hasSettingPanel: false,
                closeAction: 'hide'
            });
            if (typeof rtqWindowGroup != 'undefined') {
                rtqWindowGroup.register(this.win);
            }
            this.win.hide();
        }
    },
    _buildDataGrid: function(datagridwrap){
        var self = this;
        return new Util.DataGrid(datagridwrap, {}, {
            column: this.config.columns,
            htmlLayer: 'div',
            autoWidth: true,
            indexColKey: 'rowid',
            cellResize: false,
            cellRearrange: false,
            sortable: false,
            height: 275
        }, {
            onRowSelected: function(a, b){
                self._onDatagridRowSelected(a, b);
            },
            onRowRemove: function(rowid){
                self.removeRow(rowid);
            },
            onRowContextmenu: function(e, row){
                if(row.data.InvalidTicker || gData[row.data.gkey].type == 3) {
                   return;
                }
                if (typeof self.callback.onRowContextmenu == 'function') {
                    var obj = {};
                    obj.wsid = self.cacheObj.id;
                    obj.ticker = self._getTickerOnRow(row);
                    obj.hid = row.id;
                    obj.securityType = gData[row.data.gkey].mType;
                    var date = row.data.pdate;
                    self.callback.onRowContextmenu(e,obj);
                }
            },
            onScroll:function(l, t){
                self._activeFirstRow();
            }
        });
    },
    _removeRowData: function(rowid){
        var self=this;
        var holding = rowid;
        this._deleteRow(holding);
        this._activeFirstRow();
    },
    removeRow:function(rowid){
        this.datagrid.removeRow(rowid);
        this._removeRowData(rowid);
    },
	_getTickerOnRow: function(row){
		var ticker;
		var data = gData[row.data.gkey];
		if (row.data.InvalidTicker) {
			return null;
		}
		if (data && data["performanceId"] && data.type != 'FUTURE') {
			ticker = data["performanceId"];
		}else if (data.exch && data.ticker && data.type != 'FUTURE') {
			ticker = data.exch + ':' + data.ticker;
		}
		else {
			return null;
		}
		return ticker;
	},
    _buildEditRow: function(){
        var self = this;
        var str = '<div class="wled-active">';
        for (var i = 0; i < this.config.columns.length - 1; i++) {
            var w = this.config.columns[i];
            if(w.hide) continue;
            str += '<div class="cell">';
            str += '<input type="text"  class="qs-ui-ipt ' + w.dataIndex + '" style="width:' + (parseInt(w.width) - (i+11)) + 'px"/></div>';
        }
        str += '<div class="cell cell-go" style="width:25px" ><a href="javascript:void(0);" class="qs-ui-btn go1 ABUTTON">'+QS_Lang.watchlist["go"]+'</a></div>'
        str += '<div/>';
        self.editEl = $(str).appendTo(self.datagridWrapEl);
        self.editEl.find(".name").attr("id", "wled_ticker"); // set an id for auto complete box.
        self.editEl.find(".go1").bind("click.edit", function(){
            if (!self._validateData()) 
                return;
            if (self.selectRowKey == null && (self.currentAddKey == "" || self.currentAddKey == null)) {
                Util.message(QS_Lang.watchlist["selecttickerprompt"]);
                return;
            }
            self.selectRowKey == null ? self._addRow() : self._editRow();
            self.editEl.find("input.name").val("");
            self.currentAddKey = "";
            self._resetEdit();
        });
    },
	
    _bindACPandCal: function(){
        var self = this;
        if (this.config.ACP) {
            GB_qsAutoCompleteBox.subscription("wled_ticker", function(data){
                self._autoCPCallback(data);
            }, {
                needRemember: false,
                focusClear: false
            });
        }
        QSCAL.register(self.editEl.find(".pdate"), function(date){
            self.editEl.find(".pdate").val(QS_watchlistDataManager.formatHoldingDate(date));
        });
        self.editEl.find(".pdate").attr("readonly", true).bind("click.edit", function(e){
            var d = self.editEl.find(".pdate").val();
            if (d != "") {
                var b = d.split("-");
                d = new Date(b[2], parseInt(b[0], 10) - 1, parseInt(b[1]));
            }
            QSCAL.show($(e.target), d);
        });
    },
    _activeFirstRow: function(){
        if(this.editInput){
            this.editInput.attr("disabled", false);
    		Util.DelayRun('editdialog_editrow',this._adjustEditRow,100, this);
            this.selectRowKey = null;
            this._resetEdit();
            this._changeEditPannelPosition(this.datagridHeadHeight);
        }
    },
	_adjustEditRow:function(){
        if(this.datagrid.scrollPanel.scrollbarY.isShow){
            this.editEl.css({width:"543px"});
        }else{
            this.editEl.css({width:"556px"});
        }
    },
    _onDatagridRowSelected: function(a, b){
        this.editInput.attr("disabled", true);
		Util.DelayRun('editdialog_editrow',this._adjustEditRow,100, this);
        var el = $(b.dom);
        this.selectRowKey = b.data.rowid;
        this.currentEditDom = b;
        this.editEl.show();
        this._changeEditPannelPosition(el.position().top + this.datagrid.el.find(".rtq-grid-hd").height() + this.datagridHeadHeight);
        for (var key in b.data) {
            this.editEl.find("." + key).val(b.data[key]);
        }
    },
    _saveToWatchList: function(){
        this._mergeAction();
        if (typeof this.cacheObj.data=='undefined') {
            var name = this.el.find("div.hd").find("input").val();
            if (name == "" || $.trim(name) == '') {
                Util.message(QS_Lang.watchlist["enternameprompt"]);
                return false;
            }
            var self = this;
            this.cacheObj.name=name;
            var result=this._stackmapToArry(this.cmd.ADD);
            if(result.length>0){
                this.cacheObj.data=result;
            }
            if(this.callback.createValidation(this.cacheObj)){
                this.callback.createData(this.cacheObj);

                return true;
            }else{
                delete this.cacheObj.data;
                return false;
            }
        }
        else {
            this.cacheObj.newData=this._stackmapToArry(this.cmd.ADD);
            this.cacheObj.delData=this._stackmapToArry(this.cmd.DEL);
            this.cacheObj.ediData=this._stackmapToArry(this.cmd.EDIT);
            this.callback.saveData(this.cacheObj);
        }
        return true;
    },
    hide: function(){
        if (typeof this.win != 'undefined') {
            this.win.hide();
        }else{
            this.el.hide();
        }
        this.isOpen = false;
        this.operateStack = {
            '1': {},
            '2': {},
            '3': {}
        };
    },
    show:function(){
        this.isOpen = true;
        if(typeof this.win!='undefined'){
            this.win.show();
        }else{
            this.el.show();
        }
    },
    isShow:function(){
        return this.isOpen;
    },
    _addRow: function(){
        var rowid = this._generateHoldingID();//holdingid;
        var tempRank = this._setRank();
        var data = {
            rowid: rowid,
            gkey: this.currentAddKey,
            rank: tempRank,
            name: gData[this.currentAddKey].ticker,
            shares: this.edittingData.shares,
            pdate: this.edittingData.pdate,
            pprice: this.edittingData.pprice,
            commission: this.edittingData.commission
        };
        this.datagrid.addRow(data, null, 0);
        var holding = {
            SecId: gData[this.currentAddKey]['secId'],
            Quantity: this.edittingData.shares,
            PurchasePrice: this.edittingData.pprice,
            Comm: this.edittingData.commission,
            Date: this.edittingData.pdate,
            Rank: tempRank,
            HldgId: rowid,
            gkey: this.currentAddKey
        };
        this._pushAction(this.cmd.ADD, holding);
    },
    _editRow: function(){
        var curRowData = this.currentEditDom.data;
        var map = this.currentEditDom.DOMMap;
        map.shares.innerHTML = curRowData.shares = this.edittingData.shares;
        map.pdate.innerHTML = curRowData.pdate = this.edittingData.pdate;
        map.pprice.innerHTML = curRowData.pprice = this.edittingData.pprice;
        map.commission.innerHTML = curRowData.commission = this.edittingData.commission;
        var tempRank = curRowData.rank;
        var rowid = this.selectRowKey;
        var holding = {
            SecId: curRowData.gkey==undefined? curRowData.name:gData[curRowData.gkey]['secId'],
            Quantity: this.edittingData.shares,
            PurchasePrice: this.edittingData.pprice,
            Comm: this.edittingData.commission,
            Date: this.edittingData.pdate,
            Rank: tempRank,
            HldgId: rowid,
            gkey: curRowData.gkey
        };
        this._pushAction(this.cmd.EDIT, holding);
        this._activeFirstRow();
    },
    _deleteRow: function(holdingId){
        var holding = {
            HldgId: holdingId
        };
        this._pushAction(this.cmd.DEL, holding);
        this._updateAction(holdingId);
        this._activeFirstRow();
    },
    _validateData: function(){
        this.edittingData.ticker = this.editEl.find("input.name").val();
        var shares=this.editEl.find("input.shares").val();
        if(parseFloat(shares,10)<=0){
            Util.message(String.format(QS_Lang.watchlist["sharenumprompt"],shares));
            return false;
        }
        this.edittingData.shares = this._formatMoney(shares,'shares');
        if (this.edittingData.shares == "N") 
            return false;
        this.edittingData.pdate = this.editEl.find("input.pdate").val();
        var price=this.editEl.find("input.pprice").val();
        if(parseFloat(price,10)<=0){
            Util.message(String.format(QS_Lang.watchlist["pricenumprompt"],price));
            return false;
        }
        this.edittingData.pprice = this._formatMoney(price,'purchase price');
        if (this.edittingData.pprice == "N") 
            return false;
        this.edittingData.commission = this._formatMoney(this.editEl.find("input.commission").val(),'commission');
        if (this.edittingData.commission == "N") 
            return false;
        if (this.edittingData.ticker == null || this.edittingData.ticker == "") {
            Util.message(QS_Lang.watchlist["selecttickerprompt"]);
            return false;
        }
        if (GOLBAL_DATA.IsSeamLessLogin && this.edittingData.shares < 1) {
            Util.message(QS_Lang.watchlist["sharenumpromptforseamless"]);
            this.edittingData.shares = "1";
            return false;
        }
        if (this.edittingData.pdate == "") {
            this.edittingData.pdate = QS_watchlistDataManager.formatHoldingDate(new Date());
        }
        if(!this.config.ACP){
            this.currentAddKey=this.edittingData.ticker;
        }
        return true;
    },
    _formatMoney: function(num,title){
        if (!/^(\+|-)?(\d+)(\.\d+)?$/.test(num)) {
            Util.message(String.format(QS_Lang.watchlist["formatwrong"], num));//
            return "N";
        }
        var sign = RegExp.$1, b = RegExp.$2, decimal = RegExp.$3;
        b = b.replace(/^0*/, '');//trim pre 0
        if (parseFloat(b,10) > 0) {
            var temp = sign;
            if ($.trim(temp) == "-") {
                Util.message(String.format(QS_Lang.watchlist["numberprompt"],title,num));
                return "N";
            }
            sign = temp;
        }
        else 
            b = 0;
        return String.format("{0}{1}", b, decimal);
    },
    _resetEdit: function(ticker){
        if(typeof ticker == 'undefined'){
            this.editEl.find("input.name").val("");
        }
        this.editEl.find("input.shares").val("1");
        this.editEl.find("input.pdate").val(QS_watchlistDataManager.formatHoldingDate(new Date()));
        this.editEl.find("input.pprice").val("1");
        this.editEl.find("input.commission").val("0");
    },
    _autoCPCallback: function(pid){
        var self = this;
        if (typeof this.tValidation != 'undefined') {
            this.tValidation.checkTickers(pid, function(data){
                if (data.length == 0) {
                    Util.message(QS_Lang.watchlist["tickerinvalidprompt"]);
                }
                else {
                    self._resetEdit(true);
                    self.currentAddKey = data[0];
					var price=GB_DataManager.getMarketQuoteData(data[0], "LastPrice");
                    if (price&&price.value) {
                        var obj = self.editEl.find("input.pprice");
                        if (obj.val() == "1") {
                            obj.val(price.value);
                        }
                    }
                }
            });
        }
    },
    _changeEditPannelPosition: function(y){
        this.editEl.css({
            left: 0,
            top: y
        });
    },
	getID:function(){
		if(this.cacheObj){
			return this.cacheObj.id;
		}else{
			return null;
		}
	},
    open: function(obj){//{id:wlid,name:wlname,data:holdings, type: (0:pl,1:wl)}
        this.show();
        this.cacheObj=obj;
        var self = this;
        var gKey, ticker, tempRowID, oShare, PurchasePrice, Rank, Comm, PurchaseDate, dataList = [];
        this.datagrid.empty();
        if (typeof this.cacheObj.data!='undefined') {//edit
            this.el.find("div.hd").find("input").attr({
                readonly: true
            }).val(obj.name);
            if (this.win != 'undefined') {
				var qslan=QS_Lang.watchlist;
                this.win.setTitle(qslan["edittitle"] +" "+ (obj.type == 0 ? QS_Lang.watchlist["pl"] : QS_Lang.watchlist["wl"]));
            }
            for (var i = 0, k = this.cacheObj.data.length; i < k; i++) {
                var temphodings = this.cacheObj.data[i];
                Rank = (typeof temphodings['Rank'] != 'undefined') ? temphodings['Rank'] : 0;
                self.maxRank = Math.max(parseFloat(Rank, 10),self.maxRank);
                gKey = !temphodings['gkey'] ? gIdMap[temphodings['SecId']] : temphodings['gkey'];
                var exist= gData[gKey] == undefined? false:true;//20110214 invalid ticker
                ticker =exist? gData[gKey].ticker:temphodings['Ticker']||temphodings['SecId'];
                tempRowID = temphodings['HldgId'];
                oShare = (typeof temphodings['Quantity'] != 'undefined') ? temphodings['Quantity'] : '1';
                PurchasePrice = (typeof temphodings['PurchasePrice'] != 'undefined') ? temphodings['PurchasePrice'] : '1';
                Comm = (typeof temphodings['Comm'] != 'undefined') ? temphodings['Comm'] : '0';
                PurchaseDate = temphodings['Date'] ? temphodings['Date'] : QS_watchlistDataManager.formatHoldingDate(new Date());
                dataList.push({
                    gkey: gKey,
                    rowid: tempRowID,
                    rank: Rank,
                    name: ticker,
                    shares: oShare,
                    pdate: PurchaseDate,
                    pprice: PurchasePrice,
                    commission: Comm
                });
            }
            self.datagrid.reBindData(dataList);
            self._addInvalidFlag(dataList);
            self.editEl.hide();
        }
        else {//new
            if (this.win != 'undefined') {
				var qslan=QS_Lang.watchlist;
                this.win.setTitle(qslan["createtitle"] +" "+ (obj.type == 0 ? QS_Lang.watchlist["pl"] : QS_Lang.watchlist["wl"]));
            }
            
            this.el.find("div.hd").find("input").val("").attr({
               readonly: false
            });
            
            self.editEl.show();
        }
        this._resetEdit();
        this._changeEditPannelPosition(this.datagridHeadHeight);
    },
    _addInvalidFlag:function(holdIds){
        for(var i=0,l=holdIds.length;i<l;i++){
            if (this.datagrid.DOMMap[holdIds[i]["rowid"]]) {
                if (!gData[holdIds[i].gkey]) {
                    var dom=this.datagrid.DOMMap[holdIds[i]["rowid"]]['name'];
                    var el=$(dom);
                    el.addClass('invalid-symbol');
                    dom.innerHTML='<a href="javascript:void(0)" title="Invalid ticker">'+el.html()+'</a>';
                }
            }
        }
    },
    rebindData: function(wlObj){
        if (!this.isOpen) {
            return;
        }
        this.open(wlObj.profile.currentId, wlObj, wlObj.profile.type);
    },
    _generateHoldingID: function(){
        return this.newholdingID--;
    },
    _setRank: function(){
        return ++this.maxRank;
    },
    _pushAction: function(action, holding){
        this.operateStack[action][holding.HldgId] = holding;
    },
    _updateAction: function(holdingid){
        if (typeof holdingid == 'undefined') 
            return;
        if (this.operateStack[this.cmd.ADD][holdingid]) {
            delete this.operateStack[this.cmd.ADD][holdingid];
        }
        if (this.operateStack[this.cmd.EDIT][holdingid]) {
            delete this.operateStack[this.cmd.EDIT][holdingid];
        }
        if (!isNaN(holdingid) && holdingid < 0) {
            delete this.operateStack[this.cmd.DEL][holdingid];
        }
    },
    _mergeAction: function(){
        for (var obj in this.operateStack[this.cmd.EDIT]) {
            var temp = this.operateStack[this.cmd.EDIT][obj]['HldgId'];
            if (!isNaN(temp) && temp < 0) {
                if (typeof this.operateStack[this.cmd.ADD][obj] != 'undefined') {
                    this.operateStack[this.cmd.ADD][obj] = this.operateStack[this.cmd.EDIT][obj];
                }
            }
        }
    },
    _stackmapToArry: function(cmd){
        var temp = [];
        if (typeof cmd != 'undefined') {
            for (var obj in this.operateStack[cmd]) {
                if (cmd == this.cmd.DEL) {
                    temp.push(this.operateStack[cmd][obj]['HldgId']);
                }
                else {
                    temp.push(this.operateStack[cmd][obj]);
                }
            }
        }
        return temp;
    },
    clear: function(){
        for (var p in this) {
            if (!p || p == 'clear') {
                continue;
            }
            this[p] = null;
            delete this[p];
        }
    }
};

var QS_watchlistEditDialog=null;